var deletedNodeIds = new Array();
var index;
var nodeTableCount;
var startX				= 300.0;
var startY				= 50.0;
var eventW				= 35.0;
var eventH				= 35.0;
var usertaskX			= -35.0;
var usertaskW			= 105.0;
var usertaskH			= 55.0;
var exclusivegatewayX	= -3.0;
var exclusivegatewayW	= 40.0;
var exclusivegatewayH	= 40.0;
var spaceY				= 80.0;
var flowY				= 17.0;
var saveFlag = "";
var newVersion="";
$(function() {
	
	if($('select #entityType').length>0){
		$('select #entityType').select2({
			allowClear: true,
			placeholder:'请选择',
			language: "zh-CN"
		});
	}
	
	if($("select[name='entityType']").length>0){
		/**关联资料清单，和所属实体类型关系密切*/
		//$("#entityType").on('change',entityTypeChange);
	}
	
	$('#processDefinition .select2-selection').css("height","34px");
	nodeTableCount=$('#nodeTable tr').length - 1;
	jQuery.validator.addMethod('chineseCharacters',function(value,element){
		var reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
		return this.optional(element)||!(reg.test(value));
		
	},'不能输入汉字');
	jQuery.validator.addMethod('firstCharactersNum',function(value,element){
		var firstV = '';
		if(value!=''){
			firstV = value.substr(0,1);
		}	
		return this.optional(element)||("1234567890".indexOf(firstV)==-1);
	},'首字母不能为数字');
	$('#key').rules('add',{chineseCharacters:true,firstCharactersNum:true});
	validNode();
});


function validNode() {
	for(var index=0;index<nodeTableCount;index++){
		var fieldName;
		(function(index){
			$('#key_'+index).rules('add',{chineseCharacters:true,firstCharactersNum:true});
			$('#nodeName_'+index).rules('add',{firstCharactersNum:true});
			$('#seq_'+index).rules('add',{number:true});
			
		})(index);
	}
}

	
function addNode() {
	var index= nodeTableCount;
    var obj = $('#nodeTableForCopy').find('tr').clone();
	obj.html(obj.html().replace(/@index@/g,nodeTableCount++).replace("null",""));
	$('#nodeTable').append(obj);
	$('#key_'+index).rules('add',{chineseCharacters:true,firstCharactersNum:true});
	$('#nodeName_'+index).rules('add',{firstCharactersNum:true});
	$('#seq_'+index).rules('add',{number:true});
	common.repalceIndexForTable('nodeTable');

}


function removeNode1(name) {
    var checkBoxs = $("input[name=" + name + "]:checked");
    if(checkBoxs.length==0){
    	common.info('请选择一条删除的记录！');
    	return false;
    }
    checkBoxs.each(function(i) {
        if ($(this).attr('id')) {
        	deletedNodeIds.push($(this).attr('id'));
        }
        $(this).parent().parent().remove();
    });
    $("#deletedNodeIds").val(deletedNodeIds);
    common.repalceIndexForTable('nodeTable');
}

//此处保存节点 只要是对国际化后要求英文名称，（原流程节点从流程图里读取不方便，此处设计个节点表）
//对于本次修改过的的节点名称+节点key 都不做保存，仅仅对原流程图中节点保存英文 
function saveNode() {
	disableBtn();
	var options = {
		success : function(data) { 
			if (data.result == 'true') {
				common.success('保存成功',function(){
					saveFlag = 'saveProcess';
					afterSave($('#processId').val());
				});
			} else if (data.result == 'false') {
				common.info('保存失败');
				enableBtn();
			}else {
				enableBtn();
			}
		},
		dataType :  'json',
	};
	$("#processDefinition").attr("action", rcContextPath + "/processDefinition/saveProcessDefinitionNode");
	$("#processDefinition").ajaxSubmit(options);  
}

function formValid(){
	var keys = new Array();
	var seqs = new Array();
	var valid = false;
	var fqrvalid=false;
	$(".key").each(function(){
		var key = $(this).val();
		if(key!=''){
			if(key=='fqrsq_apply'){
				fqrvalid = true;
				return false;
			}
			if($.inArray(key,keys)==-1){
				keys.push(key);
			}else{
				valid = true;
				return false;
			}
		}
	});
	if(fqrvalid){
		common.info('节点KEY不能命名为fqrsq_apply！');
		return false;
	}
	if(valid){
		common.info('不能含有相同的节点KEY！');
		return false;
	}
	valid = false;
	$(".seq").each(function(){
		var seq = $(this).val();
		if(seq!=''){
			if($.inArray(seq,seqs)==-1){
				seqs.push(seq);
			}else{
				valid = true;
				return false;
			}
		}
	});
	if(valid){
		common.info('不能含有相同的顺序！');
		return false;
	}
	return true;
}

function saveProcessDefinition(){
	disableBtn();
	saveFlag = "saveProcessDefinition";
	if(!formValid()){
		enableBtn();
		return false;
	}
	var validate = $('#processDefinitionForm').data("validator");
	if (validate && !$('#processDefinitionForm').valid()) { //如果有验证 但是验证不通过
		return false;
	}
	submitForm('1');
}

function saveProcess(){
	disableBtn();
	saveFlag = "saveProcess";
	if(!formValid()){
		enableBtn();
		return false;
	}
	var validate = $('#processDefinitionForm').data("validator");
	if (validate && !$('#processDefinitionForm').valid()) { //如果有验证 但是验证不通过
		return false;
	}
	submitForm('0');
}


function deployProcessDefinition(newVersion1){
	disableBtn();
	saveFlag = "deploy";
	newVersion=newVersion1;
	if(!formValid()){
		enableBtn();
		return false;
	}
	var validate = $('#processDefinitionForm').data("validator");
	if (validate && !$('#processDefinitionForm').valid()) { //如果有验证 但是验证不通过
		return false;
	}
	deployForm();
}

function submitForm(index){
	disableBtn();
	var options = {
			success : function(data) {
				debugger
				if (data.result == 'true') {
					afterSave(data.id);
					enableBtn();
				} else if (data.result == 'false') {
					alert('保存失败');
					enableBtn();
				}else {
					enableBtn();
				}
			},
			dataType :  'json',
	};
	if(index=='0')
		$("#processDefinitionForm").attr("action", window.base_url+"/activiti/processDefinition/saveProcess");
	else
		 $("#processDefinitionForm").attr("action", window.base_url+"/activiti/processDefinition/saveProcessDefinition");
	$("#processDefinitionForm").ajaxSubmit(options); 
	 return false;
};

function deployForm(){
	disableBtn();
	var flowDefinitionId = $('#flowDefinitionId').val();
	var processId = $('#processId').val();
	var options = {
		success : function(data) {
			debugger
			if (data.result == 'true') {
				afterSave(data.id);
				enableBtn();
			} else if (data.result == 'false') {
				alert('保存失败');
				enableBtn();
			}else {
				enableBtn();
			}
		},
		dataType :  'json',
	};
	$("#processDefinitionForm").attr("action",  window.base_url+'/activiti/processDefinition/deployProcessDefinition?newVersion='+newVersion+"&processId="+processId);
	$("#processDefinitionForm").ajaxSubmit(options); 
	 return false;
};

function afterSave(id) {
	var key = $('#key').val();
	/*if(common.getTab1('processDefinitionHome')!=null){
		common.getTab('processDefinitionHome').queryProcessDefinition();
	}
	if(common.getTab1('process')!=null){
		common.getTab('process').queryProcess();
	}
	if(common.getTab1('processHiHome'+key)!=null){
		common.getTab('processHiHome'+key).queryProcessHi();
	}*/
	var id1 = "";
	if($("#id").length>0)
		id1=$("#id").val();
	if(saveFlag == 'saveProcess'){
		common.addTab(window.base_url+'/base/actReProcdef/apply?id='+id, '流程编辑');
		if(id1=="")
			common.closeTab();
	}else if(saveFlag == 'saveProcessDefinition'){
		common.addTab(window.base_url+'/base/actReProcdef/apply?definitionId='+id, '流程编辑');
		if(id1=="")
			common.closeTab();
	}else if(saveFlag == 'deploy'){
		if($("#processId").length>0)
			common.closeTab();
		else
			common.closeTab();
	}
}

function preview(id){
	top.addTab('tabs','预览表单', 'processFormPreview'+id, rcContextPath+'/processDefinition/preview?id='+id, true);
}

function disableBtn() {
    $("#btns").find("button").each(function(i) {
        $(this).attr("disabled", true);
    });
    $("input[type='button']").each(function(i) {
        $(this).attr("disabled", true);
    });
}

function enableBtn() {
    $("#btns").find("button").each(function(i) {
        $(this).removeAttr("disabled");
    });
    $("input[type='button']").each(function(i) {
        $(this).removeAttr("disabled");
    });
}

function queryFlowClassify(){
	modalDialog.queryFlowClassifyModal("flowClassifyDialog",confirmFunFlowClassify,function(){
		var entityType = $('#entityType').val();
		$("#entityType1").val(entityType);
		$(".modal-title").html("<b>流程分类</b>");
	},
	false);
}

function confirmFunFlowClassify(){
	var rowscontent = $('#'+modalDialog.modalGrid).bootgrid("getSelectedRowsContent");
	if(rowscontent.length <=0){
		common.info('请选择需要添加的记录。');
		return false;
	}else{
		var classifyId=rowscontent[0].id ==null ? "" : rowscontent[0].id;
		var classifyName=rowscontent[0].name ==null ? "" : rowscontent[0].nameShow;

		$('#classifyId').val(classifyId);
		$('#classifyName').val(classifyName);
		
	}
	//关闭模态窗口
	common.closeModelDialog('flowClassifyDialog');
}

function queryFlowBranch(){
	modalDialog.queryFlowBranchModal("flowBranchDialog",confirmFunFlowBranch,function(){
		$(".modal-title").html("<b>流程分支</b>");
	},
	false);
}

function confirmFunFlowBranch(){
	var ids = $('#'+modalDialog.modalGrid).bootgrid("getSelectedRows");
	var rowscontent = $('#'+modalDialog.modalGrid).bootgrid("getSelectedRowsContent");
	if(rowscontent.length >1){
		common.info('只能选择一条记录。');
		return false;
	}else{
		if(rowscontent.length ==0){
			$('#flowBranchId').val("");
			$("#flowBranchName").val("");
			$("#subName").val("");
		}else{
			var flowBranchName =$(rowscontent[0]).prop('name');
			$('#flowBranchId').val(ids);
			$("#flowBranchName").val(flowBranchName);
			$("#subName").val(flowBranchName);
		}
		//关闭模态窗口
		common.closeModelDialog('flowBranchDialog');
	}
}

function resetFlowBranch(){
	$('#flowBranchId').val("");
	$("#flowBranchName").val("");
	$("#subName").val("");
}
function resetFlowClassify(){
	$('#classifyId').val("");
	$("#classifyName").val("");
}

/**
 * 资料清单配置和实体类型关系密切，实体类型改变，资料清单配置也需要改变
 * 1、存在资料清单配置更改显示
 * 2、不存在资料清单配置隐藏显示
 */
function entityTypeChange(){
	if($("#key").val()==''){
		return ;
	}
	
	var entityList= new Array('OPPORTUNITY','PROJECT','CONTRACT',
			'CUSTOMER','LEASEHOLD','AGENCY','SUBSIDIARY','SUPPLIER','OA',
			'ASSETTRANSFERCONTRACT','FINANCINGCONTRACT','MANUFACTORCONTRACT',
			'TRADE','INVOICE','AGENDA','BONDINVESTMENTCONTRACT','AIRAGREEMENT',
			'ARCHIVES','OPERATIONEVENT','ASSETTRANSFERTRADE','APLPROJECT','RENTCHECK', 
			'MAINTAIN','BFEORDER','PDPPLAN','LEASECHECK','QUALITYCLASSIFY','DERIVATIONTRADE',
			'FINANCINGSUBSIDIARY','AIRPLANEMAKER','BFESUPPLIER','LESSORCON','WITHOUTPAY',
			'MAINTENANCECONTRACT','REPAIRREFITPROJECT','OTHER_RENT_CHECK','REDUCE','ACCESSLIST','INTENTLETTER','DEPOSITDEDUCTION','RENTMONITOR');

	var entityType=$(this).val();
//	debugger;
	if($.inArray(entityType,entityList)<0&&entityType.indexOf('CONTRACT')<0){
		$("#materialDiv").css('display','none');
		$("#archiveClassifyButton").attr('disabled','disabled');
		$("#archiveClassifyId").val('');
		$("#archiveClassifyName").val('');
	}else{
		$("#materialDiv").css('display','block');
		$("#archiveClassifyButton").removeAttr('disabled');
		refreshDocumentType();
		refreshArchiveClassify();
	}
}

function refreshDocumentType(){
	if($("#key").val()==''){
		return ;
	}
	
	// 刷新资料清单列表
	$.ajax({
		type : "post",
		url : rcContextPath
				+ '/material/refreshDocumentType',
		data : {
			entityType:$("#entityType").val(),
			key:$("#key").val()
		},
		success : function(data) {

			// console.log(data);
			$('#documentParentDiv').html(data);

		}
	});
}

function refreshArchiveClassify(){
	if($("#key").val()==''){
		return ;
	}
	
	$.ajax({
		type : "post",
		url : rcContextPath
				+ '/processExtension/getProcessExtension',
		data : {
			entityType:$("#entityType").val(),
			key:$("#key").val()
		},
		success : function(data) {
			
			$("#archiveClassifyId").val(data.archiveClassifyId);
			$("#archiveClassifyName").val(data.archiveClassifyName);

		}
	});
}

